<script lang="ts" setup>
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm, type VbenFormProps } from '#/adapter';
import {grantRole} from '#/api/system/user';

const record = ref();
const gridApi = ref();
const formSchamas: VbenFormProps = {
  schema: [
    {
      fieldName: 'user_id',
      label: '用户ID',
      component: 'Input',
      ifDetail: false,
      dependencies: {
        show: false,
        triggerFields: ['userId'],
      },
    },
    {
      fieldName: 'role_id_list',
      label: '选择角色',
      component: 'ApiSelect',
      componentProps: {
        placeholder: '请选择角色',
        allowClear: true,
        api: '/system/role',
        mode: 'multiple',
        params: {
          format:'select',
          enabled: 1,
          page: 1,
          limit: 1000,
        },
      },
      formItemClass: 'col-span-12',
    },
  ],
};
const [GrantRoleForm, formApi] = useVbenForm({
  showDefaultActions: false,
  ...formSchamas,
});
const [Modal, modalApi] = useVbenModal({
  onOpenChange(isOpen) {
    record.value = isOpen ? modalApi.getData()?.record : {};
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;
    const uniqueRoleId = [...new Set(record.value.roles.map(item => item.id))];
    formApi.setValues({
      user_id: record.value.id,
      role_id_list:uniqueRoleId || [],
    });
  },
  onConfirm() {
    formApi.validate().then(async (e: any) => {
      if (e.valid) {
        const values = await formApi.getValues();
        modalApi.setState({ loading: true, confirmLoading: true });
        grantRole(values)
          .then(() => {
            message.success('保存成功');
            gridApi.value.reload();
            modalApi.close();
          })
          .finally(() => {
            modalApi.setState({ loading: false, confirmLoading: false });
          });
      }
    });
  },
});
defineExpose(modalApi);
</script>
<template>
  <Modal class="w-[60%]" title="授权角色">
    <GrantRoleForm />
  </Modal>
</template>
